<template>
	<view class="add_bill_box">
		<Tips/>
		<view class="choose">
			<uni-segmented-control 
				:current="formData.in_out_type" 
				:values="items" 
				style-type="button"
				:active-color="primary_light_color" 
				@clickItem="onChooseFun" />
		</view>
		<view class="bill_input">
			<MyInput 
				label="金额" 
				:fontSize="formData.money==='' ? '30rpx' : '70rpx'" 
				:color="primary_hot_color" 
				:borderColor="primary_line_color"
				:focus="false"
				v-model="formData.money"
				placeholder="输入金额"
				vertical=""
				inputWidth="84%"
				height="80rpx"
				type="digit"/>
				<!-- 计算 -->
		</view>
		<view class="tip">分类</view>
		<scroll-view :show-scrollbar="true" scroll-y="true" class="scroll-Y">
			<view class="bill_type_box">
				<BillTypeCard 
					:checkedBillType="checkedBillType" 
					@chooseBillTypeFunEmit="chooseBillTypeFun"
					:isShowEdit="true"
					:showBillTypeList="showBillTypeList"/>
			</view>
		</scroll-view>
		<view class="tip">
			时间
		</view>
		<view class="time">
			<uni-datetime-picker :clear-icon="false" type="datetime" v-model="formData.time" @change="changeLog" />
		</view>
		<AdBanner />
		<view class="tip">账单凭证（支持多张图片）</view>
		<view class="proof">
			<view class="img" @click="uploadImg" style="background-color: rgba(0, 0, 0, 0.05);width:150rpx;height:150rpx;">
				<Avatar
					size="100rpx"
					:isAllowPreview="false"
					radius="10rpx"
					fileName="addImg.png" 
					:joinUrlFun="joinVoteImg"/>
			</view>
			<template v-for="item in imgArr">
				<view class="img" v-if="item!==''" :key="item">
					<view
						class="close_btn"
						@click.stop="deleteImg(item)"
					>
						<MyIcons size="30rpx" :src="joinSystemPath('closeRed2.png')"/>
					</view>
					<Avatar :isAllowPreview="true" radius="0rpx" :size="imgSize" :fileName="item" :joinUrlFun="joinBillProof"/>
				</view>				
			</template>
		</view>
		<view class="tip">备注</view>
		<view class="info" style="margin-top: -20rpx;">
			<MyInput :focus="false" placeholder="点我输入备注" v-model="formData.info"/>
		</view>
		<view class="submit_box">
			<MyButton :clickFun="submitBillFun" :bgc="primary_light_color">保存</MyButton>
		</view>
		<MyModal :openModalFlag="modalBillTypeFlag" :okFun="submitBillType">
			<template #title>
				{{billModalTitle}}
			</template>
			<template #content>
				<SetBillType @getBillTypeListEmit="getBillTypeList" :setBillType="setBillType" :clickSubmitBillTypeFlag="clickSubmitBillTypeFlag"/>
			</template>
		</MyModal>
		<!-- <numComponter /> -->
	</view>
</template>

<script setup>
	import {ref,onDeactivated, watch, nextTick,computed} from 'vue'
	
	import MyInput from '@/components/MyInput/MyInput.vue'
	import Avatar from '@/components/Avatar/Avatar.vue'
	import MyButton from '@/components/MyButton/MyButton.vue'
	import Tips from '@/components/Tips/Tips.vue'
	import MyModal from '@/components/MyModal/MyModal.vue'
	import SetBillType from '@/components/Dormitory/SetBillType/SetBillType.vue'
	import BillTypeCard from '@/components/Dormitory/BillTypeCard/BillTypeCard.vue'
	import AdBanner from '@/components/AdBanner/AdBanner.vue'
	import numComponter from '@/components/numComponter/numComponter.vue'
	
	import {uploadImgHook} from '@/hooks/uploadImg.js'
	
	import {
		openMessageAuth
	} from '@/utils/messageAuth.js'
	
	import {
		onLoad
	} from '@dcloudio/uni-app'
	
	import {
		dynamicStyleStore
	} from '@/stores/dynamicStyle.js'
	import {
		userStore
	} from '@/stores/user'
	
	import {
		DormitoryModel
	} from '@/service/model/dormitory.js'
	
	import {
		verifyIsLogin,
		verifyFormData,
		verifyIsShowChooseAd
	} from '@/hooks/verify.js'
	
	import {
		deleteLot,
		toTime
	} from '@/utils/changeData.js'
	import {
		joinSystemPath,
		joinBillProof,
		joinVoteImg
	} from '@/utils/imgJoinName.js'
	import {
		BillTypeSet
	} from '@/enum/GlobalEnum.js'
	
	import moment from 'moment'
	
	const dynamicStyle_store = dynamicStyleStore()
	const user_store = userStore()
	const dormitoryModel = new DormitoryModel()
	
	const {
		primary_light_color,
		primary_cool_color,
		primary_hot_color,
		primary_line_color,
		shallow_text_color,
		cool_border_color,
		primary_text_color
	} = dynamicStyle_store.dormitoryStyle	
	
	const items = ref(['支出','收入'])
	const money = ref(0)
	const checkedBillType=ref()
	const formData=ref({
		in_out_type:0,
		money:"",
		info:'',
		proof_url:'',
		time:Date.now()
	})
	
	const formDataSchema={
		time:{
			required:true,
			tip:'日期'
		}
	}
	
	const dormitoryAllId=uni.getStorageSync('homeData')
	
	const modalBillTypeFlag = ref(0)
	const clickSubmitBillTypeFlag = ref(0)
	const billModalTitle=ref('')
	const setBillType=ref({})
	const isPrivacy = computed(()=>user_store.userInfo.isPrivacy)
	const imgArr = computed(()=>formData.value?.proof_url?.split(',') || [])
	//点击提交修改账单类型
	const submitBillType=()=>{
		clickSubmitBillTypeFlag.value = Math.random()
	}
	
	//选择收入支出类型
	const onChooseFun=(e)=>{
		formData.value.in_out_type = e.currentIndex
		showBillTypeList.value = billTypeList.value.filter(item=>item.in_out_type === formData.value.in_out_type)
		addBillTypeAdmin()
		checkedBillType.value=showBillTypeList.value[0].id
	}
	const timer=ref(null)
	//选择账单类型
	const chooseBillTypeFun=(item)=>{
		if(item.id==='0'){
			modalBillTypeFlag.value=Math.random()
			setBillType.value={in_out_type:formData.value.in_out_type}
			billModalTitle.value=`添加${items.value[formData.value.in_out_type]}类型`
			checkedBillType.value=''
		}else{
			if(timer.value){
				const {allowSet} = item
				if(allowSet===BillTypeSet.UN_ALLOWSET) return
				modalBillTypeFlag.value=Math.random()
				billModalTitle.value=`修改${items.value[formData.value.in_out_type]}类型`
				setBillType.value=item
				clearTimeout(timer.value)
				timer.value=null
			}else{
				timer.value=setTimeout(()=>{
					clearTimeout(timer.value)
					timer.value=null
				},300)
			}
			checkedBillType.value = item.id
		}
	}
	//选择时间
	const changeLog=(e)=>{
		formData.value.time = e
	}
	const deleteImg=(item)=>{
		const arr = formData.value?.proof_url?.split(',') || []
		console.log(arr,'数据',formData.value.proof_url,item)
		const index = arr.findIndex(i=>i===item)
		if(index!==-1){
			arr.splice(index,1)
		}
		formData.value.proof_url=arr.join(',')
	}
	
	//提交
	const submitBillFun=async()=>{
		verifyIsLogin()
		verifyFormData(formData.value,formDataSchema)
		if(!checkedBillType.value){
			return uni.$emit('tips','请选择账单类型','warn')
		}
		if(Number(formData.value.money)>10000000 || String(Number(formData.value.money)).includes('e')){
			return uni.$emit('tips','金额较大，请斟酌输入','info')
		}
		if(Number(formData.value.money)<=0){
			return uni.$emit('tips','金额不能小于等于0','info')
		}
		verifyIsShowChooseAd(getCurrentPages(),'记账')
		formData.value.money = Number(Number(formData.value.money).toFixed(2))
		
		if(isEditor.value){
			const {data,success} = await dormitoryModel.patchBill({
				...formData.value,
				time:toTime(formData.value.time)
			},chooseBillByEditor.value.id,checkedBillType.value,dormitoryAllId.dormitory_id)
			if(success){
				const callback=()=>{
					uni.$emit('tips','修改成功','success')
					setTimeout(()=>{
						uni.navigateBack()
					},500)
				}
				openMessageAuth(callback,{})
			}
		}else{
			const {data,success}=await dormitoryModel.postAddBill({
				...formData.value,
				time:toTime(formData.value.time)
			},checkedBillType.value,dormitoryAllId.dormitory_id)
			if(success){
				uni.$emit('tips',data,'success')
				openMessageAuth(uni.redirectTo,{
					url:`/pages/Dormitory/Bills/Bills?isAddBillPageGo=true`
				})
			}
		}
	}
	
	//账单类型管理item
	const addBillTypeAdmin=()=>{
		showBillTypeList.value.push(
			{
				"id": "0",
				"name": "添加",
				"iconPath": "billTypeAdd.png"
			})
	}
	
	//账单类型
	const billTypeList = ref([])
	const showBillTypeList=ref([])
	const init=()=>{
		billTypeList.value=[]
		showBillTypeList.value=[]
	}
	const getBillTypeList=async(chooseBillTypeId)=>{
		init()
		const {data,success} = await dormitoryModel.getBillTypeList({},dormitoryAllId.dormitory_id)
		if(success){
			billTypeList.value = data
			showBillTypeList.value = billTypeList.value.filter(item=>item.in_out_type === formData.value.in_out_type)
			addBillTypeAdmin()
			checkedBillType.value= chooseBillTypeId || showBillTypeList.value[0].id
		}
	}
	
	const imgSize=ref(0)
	const alignInfo=ref('')
	watch(()=>formData.value.proof_url,()=>{
		if(formData.value.proof_url.length>1){
			imgSize.value = '150rpx'
			alignInfo.value='center'
		}else{
			imgSize.value = '0rpx'
			alignInfo.value=''
		}
	},{immediate:true})
	
	//封面上传
	const uploadImg=()=>{
		verifyIsLogin()
		uni.$emit('checkUserPrivacyProtocol')
		if(!isPrivacy.value){
		    return
		}
		uploadImgHook("uploadBillProof",`/upload/bill/proof`)
	}
	
	//监听图片上传成功
	uni.$on('uploadBillProof',function(data){
		;(()=>{
			if(data){
				if(!formData.value.proof_url){
					formData.value.proof_url = data
				}else{
					formData.value.proof_url = formData.value.proof_url+','+data
				}
			}
		})()
	})
	
	const isEditor=ref(false)
	const chooseBillByEditor=ref({})
	
	onLoad((opt)=>{
		if(opt.bill_id){
			chooseBillByEditor.value = uni.getStorageSync('editorBill')
			const {
				in_out_type,
				money,
				info,
				proof_url,
				time,
				billType
			}=chooseBillByEditor.value
			formData.value={
				in_out_type,
				money,
				info,
				proof_url,
				time
			}
			isEditor.value=true
			getBillTypeList(billType.billType_id)
		}else{
			isEditor.value=false
			getBillTypeList()
		}
		nextTick(()=>{
			uni.$emit('checkUserPrivacyProtocol')
		})
		nextTick(()=>{
			uni.$emit('autoShowPushScreenAd')
		})
	})
	
	onDeactivated(()=>{
		uni.$off('uploadBillProof')
	})
</script>

<style lang="less">
	.text_ellipsis {
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	.add_bill_box{
		width: 100%;
		height: calc(100vh);
		padding: 20rpx;
		.choose{
			width: 94%;
		}
		.bill_input{
			margin-top: 20rpx;
			height: 100rpx;
			width:100%;
		}
		.tip{
			color: v-bind(shallow_text_color);
			font-size: 25rpx;
			margin: 20rpx 0;
		}
		.scroll-Y{
			max-height: calc(20vh);
			.bill_type_box{
				width: 94%;
				display: flex;
				justify-content: center;
			}
		}
		.proof{
			display: grid;
			grid-template-columns: repeat(4,1fr);
			align-items: center;
			gap: 30rpx;
			width: 94%;
			.img{
				display: flex;
				justify-content: center;
				align-items: center;
				position: relative;
				.close_btn{
					position: absolute;
					top: -16rpx;
					right: -20rpx;
				}
			}
		}
		.time{
			width: 94%;
		}
		.submit_box{
			margin-top: 40rpx;
			width: 94%;
		}
	}
</style>
